package fi.tuomio.helloscala
import java.net._
import java.io._

object DiscBot {

	val random = new java.util.Random()

	def main(args: Array[String]) {
		val ia = InetAddress.getByName("localhost")
		while(true) {
			val socket = new Socket(ia, 12111)	  
			try {
				client(socket)
			} catch {
			  case e:IllegalStateException => {}
			  case e:SocketException => {}     
			} finally (socket.close())
		}
	}  

	def client(socket:Socket) {
		val out = new PrintWriter(new DataOutputStream(socket.getOutputStream()))
		val in = new DataInputStream(socket.getInputStream())
		var oldAction = ""
		in.readLine
		write(out, "DisconnectingBot"+socket.getLocalPort)
		do {
			var input = in.readLine
			var output = randomAction(input, oldAction)
			oldAction = output
			write(out, output)
			Thread.sleep(10)
		} while ( true )
	}

	def write(out: PrintWriter, line:String) {
		out.println(line)
		out.flush
	}

	def randomAction(in:String, oldAction:String) : String = {
			val options = in split " "
			val directions = options(0) split ","

			if (randomPositiveInt() % 50 == 0) throw new IllegalStateException("disconnect!")

			if (random.nextBoolean) return randomSayAction()

			if ((directions.contains("r")) && random.nextBoolean) return "r"
			if ((directions.contains("l")) && random.nextBoolean) return "l"
			if (directions.contains("f")) return "f"
			if (directions.contains("r")) return "r"
			if (directions.contains("l")) return "l"
			"b"
	}

	def randomSayAction():String = {
			val actions = List("Harrrrr!!!", "BURP!!!", "I don't feel too good", "I'm off to O'Connells", "Hey, where do you think you are going, the goal is over there *points north*",
					"Who was that maude person anyway?")
					val i = randomPositiveInt() % actions.length
					actions(i)
	}

	def pickRandomDirection(in:Array[String]):String = {
			val len = in.size
			val index = randomPositiveInt % len
			in(index)
	}

	def randomPositiveInt():Int = {
			val i = random.nextInt
			if (i < 0) -i else i
	}
}
